package com.chenye.configuration;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


/**
 * @Auther:chenye
 * @Data:2018/4/11
 * @Description:
 */
@Controller
@RequestMapping("retry")
public class TestSpringRetry implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Retryable(value={AException.class},
            maxAttempts=2,
            backoff = @Backoff(delay = 2000L,multiplier = 1))
    @RequestMapping("begin")
    @ResponseBody
    public String retry()throws Throwable{
        System.out.println("进入方法");

        throw new AException("testException");
    }
    @Recover
    @ResponseBody
    public String recover(AException a){
        System.out.println("this is a:"+a.getName());
        return "01234567890";
    }

    @RequestMapping("async")
    @ResponseBody
    public void testAsync() throws ExecutionException, InterruptedException {
        System.out.println("start async");
        TestAsync testAsync = applicationContext.getBean(TestAsync.class);
        Future future = testAsync.run1();
        if(future.isDone()){
            System.err.println(future.get());
        }
        Future future1 = testAsync.run2();
        if(future1.isDone()){
            System.err.println(future1.get());
        }
        System.out.println("end async");
    }

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}

